package rpcjson

import (
	"context"
	"github.com/pkg/errors"
	"gykjgit.dccnet.com.cn/chain/swarm/client"
	"gykjgit.dccnet.com.cn/chain/swarm/rpcjson/model"
)

// Network Network
type Network struct{}

// Create Create a network
func (Network) Create(req model.ReqNetworkCreate, resp *model.RespNetworkCreate) error {
	req.Options.CheckDuplicate = true
	response, err := client.ObtainClient().NetworkCreate(context.Background(), req.Name, req.Options)
	if nil != err {
		return errors.Wrap(err, "NetworkCreate error")
	}
	resp.Response = response
	return nil
}

// Remove Remove one or more networks
func (Network) Remove(req model.ReqNetworkRemove, _ *model.RespNetworkRemove) error {
	if err := client.ObtainClient().NetworkRemove(context.Background(), req.NetworkID); nil != err {
		return errors.Wrap(err, "NetworkRemove error")
	}
	return nil
}

// Inspect Display detailed information on one or more networks
func (Network) Inspect(req model.ReqNetworkInspect, resp *model.RespNetworkInspect) error {
	resource, data, err := client.ObtainClient().NetworkInspectWithRaw(context.Background(), req.NetworkID, req.Options)
	if nil != err {
		return errors.Wrap(err, "NetworkInspectWithRaw error")
	}
	resp.Resource = resource
	resp.Data = data
	return nil
}

// List List networks
func (Network) List(req model.ReqNetworkList, resp *model.RespNetworkList) error {
	resource, err := client.ObtainClient().NetworkList(context.Background(), req.Options)
	if nil != err {
		return errors.Wrap(err, "NetworkList error")
	}
	resp.Resource = resource
	return nil
}

// Connect Connect a container to a network
func (Network) Connect(req model.ReqNetworkConnect, _ *model.RespNetworkConnect) error {
	err := client.ObtainClient().NetworkConnect(context.Background(), req.NetworkID, req.ContainerID, req.Config)
	if nil != err {
		return errors.Wrap(err, "NetworkConnect error")
	}
	return nil
}

// Disconnect Disconnect a container from a network
func (Network) Disconnect(req model.ReqNetworkDisconnect, _ *model.RespNetworkDisconnect) error {
	err := client.ObtainClient().NetworkDisconnect(context.Background(), req.NetworkID, req.ContainerID, req.Force)
	if nil != err {
		return errors.Wrap(err, "NetworkDisconnect error")
	}
	return nil
}

// Prune Remove all unused networks
func (Network) Prune(req model.ReqNetworkPrune, resp *model.RespNetworkPrune) error {
	report, err := client.ObtainClient().NetworksPrune(context.Background(), req.Filters)
	if nil != err {
		return errors.Wrap(err, "NetworksPrune error")
	}
	resp.Report = report
	return nil
}
